package com.atguigu.tingshu.cdc.handler;

import com.atguigu.tingshu.cdc.entity.CdcEntity;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import top.javatool.canal.client.annotation.CanalTable;
import top.javatool.canal.client.handler.EntryHandler;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
@CanalTable("album_info") //监听变更表
public class CdcEntityHandler implements EntryHandler<CdcEntity> {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RabbitService rabbitService;

    /**
     * album_info表中有数据新增的时候 会回调该方法
     * @param cdcEntity
     */
    @Override
    public void insert(CdcEntity cdcEntity) {
        EntryHandler.super.insert(cdcEntity);
    }

    @Override
    public void update(CdcEntity before, CdcEntity after) {


        //方案一：先删缓存再删数据库方法
//        String cacheKey = "cache:info:" + after.getId();
//
//        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);
//        try{
//            scheduledExecutorService.schedule(new Runnable() {
//                @Override
//                public void run() {
//                    redisTemplate.delete(cacheKey);
//                }
//            },300, TimeUnit.MILLISECONDS);
//        }catch (Exception e){
//            //todo 删除失败重删机制
////            rabbitService.sendMessage()
//        }

        //方案二 先更新数据库在删缓存
        String cacheKey = "cache:info:" + after.getId();
        try{
            redisTemplate.delete(cacheKey);

        }catch (Exception e){
            //todo 删除失败重删机制
//            rabbitService.sendMessage()
        }

    }

    @Override
    public void delete(CdcEntity cdcEntity) {
        EntryHandler.super.delete(cdcEntity);
    }
}
